package com.ilxqx.framework.system.service.impl;

import com.ilxqx.framework.system.constant.TableFieldConstants;
import com.ilxqx.framework.system.repository.FrameworkRepository;
import com.ilxqx.framework.system.service.PageableService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.Assert;

/**
 * 分页服务接口实现类
 * @author venus
 */
public abstract class AbstractPageableServiceImpl<T, ID> extends AbstractCrudServiceImpl<T, ID> implements PageableService<T, ID> {

    /**
     * Jpa仓库实现注入
     */
    private FrameworkRepository<T, ID> repository;

    public AbstractPageableServiceImpl(FrameworkRepository<T, ID> repository) {
        super(repository);
        this.repository = repository;
    }

    /**
     * 根据分页和排序获取一页记录
     *
     * @param pageable 分页和排序对象
     * @return 一页记录
     */
    @Override
    public Page<T> getPage(Pageable pageable) {
        return this.repository.findAll(pageable);
    }

    /**
     * 根据分页、排序和操作用户ID获取一页记录
     *
     * @param pageable        分页和排序对象
     * @param operationUserId 操作用户ID
     * @return 一页记录
     */
    @Override
    public Page<T> getPage(Pageable pageable, ID operationUserId) {
        Assert.notNull(operationUserId, "操作用户ID不能为空");
        return this.repository.findAll((Specification<T>) (root, query, criteriaBuilder) ->
                criteriaBuilder.and(criteriaBuilder.equal(root.get(TableFieldConstants.OPERATION_USER_ID_FIELD_NAME), operationUserId)), pageable);
    }

}
